package com.zsy.service.Impl;

import com.zsy.dao.AddressBookDao;
import com.zsy.exception.CustomException;
import com.zsy.pojo.AddressBook;
import com.zsy.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.Inet4Address;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookDao addressBookDao;

    @Override
    public void save(AddressBook addressBook) {
        addressBookDao.save(addressBook);
    }

    @Override
    public List<AddressBook> queryAddressList(Long userId) {
        List<AddressBook> addressBookList =  addressBookDao.queryAddressList(userId);
        return addressBookList;
    }

    //更新默认地址
    @Override
    @Transactional
    public void updateDefaultAddress(AddressBook addressBook) {
        //1. 把该用户地址全部修改为非默认
        addressBookDao.removeDefaultAddress(addressBook.getUserId());
        //2 重新设置当前地址为默认地址
        addressBookDao.updateDefaultAddress(addressBook);

    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookDao.getById(id);
    }

    @Override
    public AddressBook getDefaultAddress(Long currentId) {
        return addressBookDao.getDefaultAddress(currentId);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBookDao.update(addressBook);
    }

    @Override
    public void delete(Long ids) {
        Integer i = addressBookDao.findByisDefault(ids);
        if(i==0){
            addressBookDao.delete(ids);
        }else {
            throw new CustomException("此地址是默认地址，无法删除");
        }
    }
}
